<%@ page import="com.ws.ssmzongjie3.util.Res" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修改用户</title>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css">

    <script src="${pageContext.request.contextPath}/bootstrap/js/jquery-2.1.0.min.js"></script>
    <script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>
    <style>
        .cus-container {
            width: 800px; /* 缩小容器宽度 */
            margin: 0 auto; /* 居中显示 */
        }
        .form-group {
            margin-bottom: 15px; /* 调整表单元素间距 */
        }
        .modal-content {
            padding: 0 15px 15px; /* 缩小内边距 */
        }
    </style>
</head>
<body>
    <div class="container cus-container">
        <h3 class="text-center">修改用户信息</h3>
        <form action="${pageContext.request.contextPath}/user/update" method="post" enctype="multipart/form-data">
            <input type="hidden" name="user_id" value="${user.user_id}">
            <div class="form-group">
                <label for="username">用户名：</label>
                <input type="text" class="form-control" name="u_name" id="username" value="${user.u_name}" placeholder="请输入用户名">
                <span class="error" id="usernameError" style="display: none; color: red;"></span> <!-- 添加错误提示区域 -->
            </div>
            <div class="form-group">
                <label for="password">密码：</label>
                <input type="password" class="form-control" name="u_pass" id="password" value="666666" placeholder="请输入密码">
            </div>
            <div class="form-group">
                <label>性别：</label>
                <label class="radio-inline">
                    <input type="radio" name="u_sex"   value="男" <c:if test="${user.u_sex=='男'}">checked</c:if> > 男
                </label>
                <label class="radio-inline">
                    <input type="radio" name="u_sex" value="女" <c:if test="${user.u_sex=='女'}">checked</c:if>> 女
                </label>
            </div>
            <div class="form-group">
                <label for="birthday">出生日期：</label>
                <input type="date" class="form-control" name="u_birthday" id="birthday" value="${user.user_birthday}" required="required" placeholder="请输入出生日期">
            </div>
            <div class="form-group">
                <label for="email">邮箱：</label>
                <input type="text" class="form-control" name="u_email" id="email" value="${user.u_email}" placeholder="请输入邮箱">
            </div>
            <div class="form-group">
                <label for="phone">手机：</label>
                <input type="text" class="form-control" name="u_phone" id="phone" value="${user.u_phone}" placeholder="请输入手机号">
            </div>
            <div class="form-group">
                <label for="image">上传图片：</label>
                <input type="file" class="form-control" name="image" id="image" multiple>
                <!-- 图片预览区域 -->
                <div id="image-preview" style="margin-top: 10px;">
                    <c:if test="${not empty user.u_avatar}">
                        <img src="<%=Res.fileUrl%>${user.u_avatar}" width="100" height="100" alt="当前头像">
                    </c:if>
                </div>
            </div>
            <div class="text-center">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="history.back()">返回</button>
            </div>
        </form>
    </div>
</body>
</html>

<script>
    // 页面加载完成后绑定事件
    $(document).ready(function() {
        // 绑定用户名输入框的blur事件
        document.getElementById('username').addEventListener('blur', checkUsername);
    });

    // 图片上传预览功能
    document.getElementById('image').addEventListener('change', function(event) {
        var preview = document.getElementById('image-preview');
        preview.innerHTML = ''; // 清空之前的预览

        var files = event.target.files;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var reader = new FileReader();

            reader.onload = (function(file) {
                return function(e) {
                    var img = document.createElement('img');
                    img.src = e.target.result;
                    img.style.width = '100px';
                    img.style.height = '100px';
                    img.style.margin = '5px';
                    preview.appendChild(img);
                };
            })(file);

            reader.readAsDataURL(file);
        }
    });

    // 用户名重名验证
    function checkUsername() {
        const username = document.getElementById('username').value.trim();
        const userId = document.querySelector('input[name="user_id"]').value;
    
        if (username.length < 3 || username.length > 20) {
            document.getElementById('usernameError').textContent = '用户名长度应在3到20个字符之间';
            document.getElementById('usernameError').style.display = 'block';
            return;
        }
    
        $.ajax({
            url: '${pageContext.request.contextPath}/user/checkUsername',
            type: 'POST',
            data: { username: username, userId: userId },
            success: function(data) {
                if (data.exists) {
                    document.getElementById('usernameError').textContent = '用户名已存在，请重新输入';
                    document.getElementById('usernameError').style.display = 'block';
                } else {
                    document.getElementById('usernameError').style.display = 'none';
                }
            },
            error: function(error) {
                console.error('Error:', error);
            }
        });
    }

    // 表单提交时再次验证用户名
    document.querySelector('form').addEventListener('submit', function(e) {
        const username = document.getElementById('username').value.trim();
        if (username.length < 3 || username.length > 20) {
            document.getElementById('usernameError').textContent = '用户名长度应在3到20个字符之间';
            document.getElementById('usernameError').style.display = 'block';
            e.preventDefault();
            return;
        }
    
        // 同步验证用户名是否重复
        $.ajax({
            url: '${pageContext.request.contextPath}/user/checkUsername',
            type: 'POST',
            data: { username: username, userId: document.querySelector('input[name="user_id"]').value },
            async: false,
            success: function(data) {
                if (data.exists) {
                    document.getElementById('usernameError').textContent = '用户名已存在，请重新输入';
                    document.getElementById('usernameError').style.display = 'block';
                    e.preventDefault();
                } else {
                    document.getElementById('usernameError').style.display = 'none';
                }
            },
            error: function(error) {
                console.error('Error:', error);
                e.preventDefault();
            }
        });
    });
</script>
